const cloud = require('wx-server-sdk');

cloud.init({
    env: 'j-1g278wytc94978ae'
});

exports.main = async (event, context) => {
    const openId = event.open_id;
    const sendId = event.id;
    const fun_name = event.fun_name;
    const collectionName = event.collection_name;
    switch (fun_name) {
        case 'get_partly_video_list':
            return get_partly_video_list(collectionName);
        case 'get_all_video_list':
            return get_all_video_list(collectionName);
        case 'get_id_video_detail':
            return get_id_video_detail(sendId, collectionName);
        case 'get_pulldown_refresh':
            return get_pulldown_refresh(collectionName);
        case 'get_openid_video_list':
            return get_openid_video_list(openId, collectionName);
        case 'get_openid_and_videoid_video_list':
            return get_openid_and_videoid_video_list(openId, sendId, collectionName);
        default:
            return {
                errMsg: '云函数没有此方法'
            }
    }
}

async function get_partly_video_list (collection_name) {
    try {
        return cloud.database().collection(collection_name).limit(8).get()
    } catch (error) {
        cloud.logger().error({
            error
        });
        return error;
    }
}

async function get_all_video_list (collection_name) {
    try {
        return cloud.database().collection(collection_name).get()
    } catch (error) {
        cloud.logger().error({
            error
        });
        return error;
    }
}

async function get_openid_video_list (openid, collection_name) {
    try {
        return cloud.database().collection(collection_name).where({
            open_id: openid
        }).get()
    } catch (error) {
        cloud.logger().error({
            error
        });
        return error;
    }
}

async function get_openid_and_videoid_video_list (openid, videoid, collection_name) {
    try {
        return cloud.database().collection(collection_name).where({
            open_id: openid,
            video_id: videoid
        }).get()
    } catch (error) {
        cloud.logger().error({
            error
        });
        return error;
    }
}

async function get_id_video_detail (Id, collection_name) {
    try {
        return cloud.database().collection(collection_name).where({
            video_id: Id
        }).get()
    } catch (error) {
        cloud.logger().error({
            error
        });
        return error;
    }
}

async function get_pulldown_refresh (collection_name) {
    try {
        return cloud.database().collection(collection_name).skip(10).get()
    } catch (error) {
        cloud.logger().error({
            error
        });
        return error;
    }
}